package user

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"hzjt-oam/admin-api/internal/config"
	"hzjt-oam/admin-api/model/user"
	"time"

	"hzjt-oam/admin-api/internal/svc"
	"hzjt-oam/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAddLogic {
	return &UserAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserAddLogic) UserAdd(req *types.AddUserReq) (resp *types.AddUserResp, err error) {
	userId, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, errors.New("验证token未通过")
	}
	user_two, err := l.svcCtx.UserModel.FindOne(l.ctx, userId)

	if _, err := l.svcCtx.UserModel.Insert(l.ctx, &user.SysUser{
		Name:           req.Name,
		NickName:       req.NickName,
		Avatar:         req.Avatar,
		Password:       config.Md5(req.Password),
		Email:          req.Email,
		Mobile:         req.Mobile,
		Status:         1,
		DeptId:         req.DeptId,
		CreateBy:       user_two.Name,
		CreateTime:     time.Now().Unix(),
		LastUpdateBy:   user_two.Name,
		LastUpdateTime: time.Now().Unix(),
		DelFlag:        0,
		RoleId:         req.RoleId,
		Age:            sql.NullInt64{},
		Sex:            sql.NullString{},
	}); err != nil {
		return nil, errors.New("添加用户出错")
	}

	return &types.AddUserResp{"成功"}, nil
}
